<template>
  <!-- 门店收益图 -->
  <div class="w-full echart-box">
    <a-skeleton-shape v-if="loading" class="w-full" style="height: 296px" />
    <template v-else>
      <a-empty
        style="background-color: rgba(248, 250, 252, 1)"
        description="根据您的筛选统计数据时发现暂无数据，请重新筛选"
        v-if="echartDataEmpty"
      />
      <div v-else class="echart-item" ref="echartBoxRef"></div>
    </template>
  </div>
</template>
<script setup lang="ts">
  import TooltipTable from '../revenue/TooltipTable.vue'

  import useEcharts from '@/hooks/useEcharts'
  import dayjs from 'dayjs'
  import { dispose } from 'echarts/core'
  import { createVNode, nextTick, onBeforeUnmount, onMounted, ref, render, watch } from 'vue'

  const props = defineProps({
    echartData: {
      type: Array,
      default: () => [],
    },
  })

  const loading = ref(true)
  const echartBoxRef = ref()

  let echartInstance: any = null
  let echart_legend: any[] = []
  let echart_axis: string[] = []
  let echart_series: any[] = []
  const echartInt = () => {
    const option: any = {
      grid: {
        top: '10%',
        left: 43,
        right: '2%',
        bottom: 0,
        containLabel: true,
      },
      tooltip: {
        trigger: 'axis',
        appendToBody: true,
        appendTo: 'body',
        enterable: true, // 鼠标是否可进入提示框浮层中
        confine: true,
        formatter: (params: any) => {
          // 挂载 maptooltip 组件
          const com = createVNode(TooltipTable, {
            dataSource: params[0]?.data,
          })
          let mountNode = document.createElement('div')
          render(com, mountNode)
          return com.el
        },
        // // 修改 echarts 默认 tooltips 样式
        extraCssText: 'padding: 0px; border-radius: 6px; border: none',
      },
      legend: {
        icon: 'circle',
        itemWidth: 10,
        top: 'bottom',
        left: 100,
        right: 100,
        data: echart_legend,
        padding: [5, 5, 25, 5],
        formatter: (name: string) => {
          if (name.length > 8) {
            return name.slice(0, 8) + '...'
          }
          return name
        },
        tooltip: {
          show: true,
        },
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: echart_axis,
        axisLine: {
          show: true,
          lineStyle: {
            color: '#eee',
          },
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          color: '#666',
          margin: 20,
        },
        axisPointer: {
          show: true,
          lineStyle: {
            color: '#4080FF',
            width: 2,
          },
        },
      },
      yAxis: {
        type: 'value',
        name: '单位: 元',
        minInterval: 1,
        nameTextStyle: {
          color: '#666',
          align: 'right',
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#eee',
          },
        },
        axisLabel: {
          color: '#666',
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: [5, 10],
            dashOffset: 5,
          },
        },
      },
      dataZoom: [
        {
          type: 'slider',
          realtime: true,
          height: 14, //组件高度
          moveHandleSize: 15,
          left: '4%', //左边的距离
          right: '4%', //右边的距离
          bottom: '0%', //下边的距离
          xAxisIndex: [0],
          showDataShadow: false,
          show: echart_axis.length > 20 ? true : false, // 是否展示
          fillerColor: 'rgba(2,110,252,1)', // 滚动条颜色
          borderColor: 'rgba(17, 100, 210, 0.12)',
          backgroundColor: 'rgba(232,244,255,0.51)', //两边未选中的滑动条区域的颜色
          handleSize: 0, //两边手柄尺寸
          showDetail: false, //拖拽时是否展示滚动条两侧的文字
          startValue: 0, // 从头开始。
          endValue: 20,
        },
        {
          type: 'inside', // 支持内部鼠标滚动平移
          startValue: 0, // 从头开始。
          endValue: 20,
          zoomLock: true, // 是否只平移不缩放
          zoomOnMouseWheel: false, // 关闭滚轮缩放
          moveOnMouseWheel: false, // 关闭滚轮平移
          moveOnMouseMove: false, // 关闭鼠标拖动平移
          preventDefaultMouseMove: false, // 鼠标移动能触发数据窗口平移
        },
      ],
      series: echart_series,
    }

    nextTick(() => {
      echartInstance = useEcharts(echartBoxRef.value)
      console.log('StoreRevenueChart', option)
      echartInstance?.setOption(option, {
        notMerge: true,
      })

      getLegendHeight(echartInstance)
    })

    loading.value = false
  }

  const getLegendHeight = (echartInstance: any) => {
    const legend = echartInstance.getModel().getComponent('legend')
    const view = echartInstance.getViewOfComponentModel(legend)
    const rect = view.group.getBoundingRect()
    echartInstance.setOption({
      grid: {
        bottom: rect.height + 10,
      },
    })
  }

  const echartDataEmpty = ref(true)
  const initEchartData = (data: any[]) => {
    echart_axis = []
    echart_series = []
    echart_legend = []
    loading.value = true

    const hasData = data?.some((item: any) => item.lineDataList?.length)

    if (!hasData) {
      loading.value = false
      echartDataEmpty.value = true
      return
    } else {
      echartDataEmpty.value = false
    }

    if (data.length > 0) {
      data.forEach((item: any) => {
        // 横坐标
        echart_axis.push(dayjs(item.date).format('MM-DD'))

        // let tmp = 0
        // 折线图数据
        item.lineDataList.forEach((lineItem: any, index: number) => {
          if (echart_series[index]?.name == lineItem.name) {
            echart_series[index].data.push({
              date: item.date,
              value: lineItem.totalAmount,
              infoList: item.infoList,
              totalRevenueAmount: item.totalRevenueAmount,
              totalExpenditureAmount: item.totalExpenditureAmount,
              totalProfitAmount: item.totalProfitAmount,
            })
          } else {
            echart_series.push({
              name: lineItem.name,
              type: 'line',
              lineStyle: {
                width: 2,
              },
              data: [
                {
                  date: item.date,
                  value: lineItem.totalAmount,
                  infoList: item.infoList,
                  totalRevenueAmount: item.totalRevenueAmount,
                  totalExpenditureAmount: item.totalExpenditureAmount,
                  totalProfitAmount: item.totalProfitAmount,
                },
              ],
            })
          }

          if (echart_legend.indexOf(lineItem.name) == -1) {
            echart_legend.push(lineItem.name)
          }
        })
      })
      echartInt()
    } else {
      echartDataEmpty.value = true
    }
  }

  onMounted(() => {
    initEchartData(props.echartData)

    window.addEventListener('resize', () => {
      getLegendHeight(echartInstance)
      echartInstance?.resize()
    })
  })

  onBeforeUnmount(() => {
    if (echartInstance) {
      dispose(echartInstance)
    }
  })

  watch(
    () => props.echartData,
    (newVal: any) => {
      initEchartData(newVal)
    },
    {
      deep: true,
    }
  )
</script>

<style lang="less" scoped>
  .echart-box {
    width: 100%;

    .echart-item {
      width: 100%;
      height: 364px;
    }
  }
</style>
